<template>
	<div class="sys-wcstask-container">
		<el-dialog v-model="state.isShowDialog" draggable :close-on-click-modal="false" width="700px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit />
					</el-icon>
					<span> {{ props.title }} </span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="任务号" prop="taskNumber"
							:rules="[{ required: true, message: '任务号不能为空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.taskNumber" placeholder="任务号" clearable
								:disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="托盘" prop="trayCode"
							:rules="[{ required: true, message: '托盘不能为空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.trayCode" placeholder="托盘" clearable
								 />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="物料号" prop="materialCode"
							:rules="[{ required: true, message: '物料号不能为空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.materialCode" placeholder="物料号" clearable
								 />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="出入口位置" prop="hoistOpening"
							:rules="[{ required: true, message: '出入口位置不能为空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.hoistOpening" placeholder="出入口位置" clearable
								 />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="任务下达时间" prop="downDate"
							:rules="[{ required: true, message: '任务下达时间', trigger: 'blur' }]">
							<el-date-picker v-model="state.ruleForm.downDate" type="datetime" placeholder="任务下达时间"
								clearable />
						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="任务完成时间" prop="finishDate"
							:rules="[{ required: true, message: '任务完成时间', trigger: 'blur' }]">
							<el-date-picker v-model="state.ruleForm.finishDate" type="datetime" placeholder="任务完成时间"
								clearable />
						</el-form-item>
					</el-col>
					<!-- 应用任务类型枚举 -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="任务类型" prop="type"
:rules="[{ required: true, message: '任务类型', trigger: 'blur' }]" @change="generateTaskNumber">
							<el-select v-model="state.ruleForm.type" placeholder="任务类型">
								<template v-for="(value, key) in TaskTypeEnum" :key="value">
									<el-option :label="TaskTypeEnumLabels[value] || '默认类型'" :value="value" />
								</template>
							</el-select>
						</el-form-item>
					</el-col>
					<!-- 应用任务状态枚举 -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="任务状态" prop="status"
							:rules="[{ required: true, message: '任务状态', trigger: 'blur' }]">
							<el-select v-model="state.ruleForm.status" placeholder="任务状态">
								<!-- 遍历去重后的枚举值 -->
								<template v-for="value in new Set(Object.values(TaskStatusEnum))" :key="value">
									<el-option :label="TaskStatusEnumLabels[value] || '默认状态'" :value="value" />
								</template>

								<el-option v-if="!Object.values(TaskStatusEnum).includes(state.ruleForm.status)"
									:label="`默认状态`" :value="state.ruleForm.status" />
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="SN码" prop="sn"
							:rules="[{ required: true, message: 'sn码非空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.sn" placeholder="SN码" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="暂存渠道" prop="channel"
							:rules="[{ required: true, message: '暂存渠道非空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.channel" placeholder="暂存渠道" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="发送次数" prop="countNumber"
							:rules="[{ required: true, message: '发送次数', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.countNumber" placeholder="发送次数" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="响应结果" prop="resPonse"
							:rules="[{ required: true, message: '响应结果', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.resPonse" placeholder="响应结果" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="是否启用" prop="isenable"
							:rules="[{ required: false, message: '必选', trigger: 'blur' }]">
							<!-- v-if="state.ruleForm.name != null" 加在是否的item上 -->
							<el-radio-group v-model="state.ruleForm.isenable">
								<el-radio :value="1">是</el-radio>
								<el-radio :value="0">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="EditWarehouse">

const TaskStatusEnum = {
	NoStarte: 1,
	Underay: 2,
	Back: 3,
	Completed: 4,
	Cancelled: 5,
	Abnormal: 6
};

const TaskStatusEnumLabels = {
	[TaskStatusEnum.NoStarte]: '未开始',
	[TaskStatusEnum.Underay]: '进行中',
	[TaskStatusEnum.Back]: '退回',
	[TaskStatusEnum.Completed]: '已完成',
	[TaskStatusEnum.Cancelled]: '已取消',
	[TaskStatusEnum.Abnormal]: '异常'
};

const TaskTypeEnum = {
	Inbound: 1,
	Outbound: 2,
	Inventory: 3,
	Other: 0,
	Temporarily: 4
};

const TaskTypeEnumLabels = {
	[TaskTypeEnum.Inbound]: '入库任务',
	[TaskTypeEnum.Outbound]: '出库任务',
	[TaskTypeEnum.Inventory]: '盘点任务',
	[TaskTypeEnum.Other]: '其他任务',
	[TaskTypeEnum.Temporarily]: '暂存出库'
};

import { reactive, ref } from 'vue';
import { dayjs, ElMessage, ElMessageBox } from 'element-plus';

import { getAPI } from '/@/utils/axios-utils';
import { WcstaskApi ,apiWcstaskMAxPost} from '/@/api-services/apis/warehouse-wcstask-api';
import { AccountTypeEnum, UpdateDictTypeInput } from '/@/api-services/models';
import { useUserInfo } from '/@/stores/userInfo';
import { WcstaskInput } from '/@/api-services/models/wcstask-input';

// 打开弹窗
const openDialog = (row: any) => {
	state.ruleForm = JSON.parse(JSON.stringify(row));
	state.isShowDialog = true;
	ruleFormRef.value?.resetFields();
};

const props = defineProps({
	title: String,
});
const emits = defineEmits(['handleQuery']);
const ruleFormRef = ref();
const state = reactive({
	isShowDialog: false,
	ruleForm: {} as WcstaskInput,
});

// 关闭弹窗
const closeDialog = () => {
	emits('handleQuery');
	state.isShowDialog = false;
};

// 取消
const cancel = () => {
	state.isShowDialog = false;
};
const maxid=async()=>{
	try {
      const response = await apiWcstaskMAxPost({});
      const maxId = response.data.result;
    } catch (error) {
      console.error('获取最大ID失败', error);
      ElMessage.error('生成任务号失败，请稍后重试');
    }
}


const generateTaskNumber=()=>{

	if (state.ruleForm.type) {
		const taskTypeLabel = TaskTypeEnumLabels[state.ruleForm.type];
		const currentDate = dayjs().format('YYYYMMDD');
		const randomNumber = Math.floor(Math.random() * 10000).toString().padStart(4, '0'); // 生成4位随机数
		state.ruleForm.taskNumber = `${taskTypeLabel}-${currentDate}-${randomNumber}-${maxid}`;
		
	}
}

// 提交
const submit = () => {
	ruleFormRef.value.validate(async (valid: boolean) => {
		if (!valid) return;
		try {
			// 转换日期格式
			const formData = {
				...state.ruleForm,
				//downDate: dayjs(state.ruleForm.downDate).isValid() ? dayjs(state.ruleForm.downDate).toISOString() : '',
				//finishDate: dayjs(state.ruleForm.finishDate).isValid() ? dayjs(state.ruleForm.finishDate).toISOString() : ''
			};

			if (state.ruleForm.id != undefined && state.ruleForm.id > 0) {

				await getAPI(WcstaskApi).apiWcstaskUpdatePost(formData);
				ElMessage.success('编辑成功');

			} else {
				await getAPI(WcstaskApi).apiWcstaskAddPost(formData);
				ElMessage.success('添加成功');
			}
		}
		catch (error) {
			//console.error('删除失败:', error);
			ElMessage.error('执行失败，请稍后重试');
		}
		closeDialog();
	}).catch(() => {
		ElMessage.info('已取消');
	});
};

// 导出对象
defineExpose({ openDialog });
</script>
